package nhatquang.gs.view;

import org.andengine.entity.Entity;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;

import android.util.Log;
import android.widget.Toast;

import nhatquang.gs.controler.FruitManager;
import nhatquang.gs.controler.ScenesManager;
import nhatquang.gs.model.BaseScene;
import nhatquang.gs.model.Public;

public class PlayerScene extends BaseScene implements IOnSceneTouchListener {
	/* ----- variable controller ---- */
	private boolean checkpause;
	private long T0;
	private long T1;
	private long T2;
	private long sumTime;
	/* ----- variable controller --- */

	/* ----- background ----- */
	private Entity mEntityBackGround;
	private Sprite mMap;
	private Sprite mPanel;
	private Sprite mBackGround;
	private Sprite mTime;
	private Sprite mPause;
	private Sprite mTimeBlue;
	private Sprite mTimeBrown;
	private AnimatedSprite[] mScore;
	private AnimatedSprite[] mTargetScore;
	private AnimatedSprite[] spriteNumberLevel;
	private AnimatedSprite mLevel;
	private int currentLeng;
	/* ----- background ------ */

	/* ---- pause game ---- */
	private Entity mEntity_PauseGame;
	private Sprite spriteBackground_PauseGame;
	private Sprite spriteMenu_PauseGame;
	private Sprite spriteResume_PauseGame;
	private Sprite spritePauseGame_PauseGame;
	private Sprite spriteOnAudio_PauseGame;
	private Sprite spriteOffAudio_PauseGame;

	/* ----- pause game ------ */

	/* ---- complete game */
	private Sprite spriteComplete;
	private Sprite spriteMenu;
	private Sprite spriteNext;
	private Sprite spriteRestart;
	/* ---- complete game */

	private FruitManager fruitMananger;
	private Entity mEntityFruit;

	public void createScene() {
		initControll();
		initBackground();
		initPlayer();
	}

	public void initControl() {
		checkpause = false;
		T0 = T1 = T2 = System.currentTimeMillis();
	}

	public void initBackground() {
		mEntityBackGround = new Entity(0, 0);

		mBackGround = new Sprite(0, 0,
				mResourcesManager.mTextureRegionBackGround_Player, VBOM);

		mMap = new Sprite(0, 290, mResourcesManager.mTextureRegionMap_Player,
				VBOM);
		mPanel = new Sprite(0, 0, mResourcesManager.mTextureRegionPanel_Player,
				VBOM);
		mTime = new Sprite(0, 212, mResourcesManager.mTextureRegionTime_Player,
				VBOM);
		mPause = new Sprite(Public.WIDTH_SCREEN
				- mResourcesManager.mTextureRegionPause_Player.getWidth(),
				mResourcesManager.mTextureRegionPanel_Player.getHeight(),
				mResourcesManager.mTextureRegionPause_Player, VBOM) {
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				initScreenPauseGame();
				return true;
			}
		};
		this.registerTouchArea(mPause);
		mTimeBlue = new Sprite(10, Public.HEIGHT_MENU - 67f,
				mResourcesManager.mTextureRegionTimeBlue_Player.getWidth(),
				mResourcesManager.mTextureRegionTimeBlue_Player.getHeight(),
				mResourcesManager.mTextureRegionTimeBlue_Player, VBOM);
		mTimeBrown = new Sprite(0, 212,
				mResourcesManager.mTextureRegionTimeBrown_Player.getWidth(),
				mResourcesManager.mTextureRegionTimeBrown_Player.getHeight(),
				mResourcesManager.mTextureRegionTimeBrown_Player, VBOM);
		mScore = new AnimatedSprite[7];
		for (int i = 0; i < 7; i++) {
			mScore[i] = new AnimatedSprite(430 - i * 14, 48,
					mResourcesManager.mTextureRegionScore_Player, VBOM);
		}

		mTargetScore = new AnimatedSprite[7];
		for (int i = 0; i < 7; i++) {
			mTargetScore[i] = new AnimatedSprite(270 - i * 16, 50,
					mResourcesManager.mTiledTextureRegionTargetScore_Player,
					VBOM);
		}
		updateScoreTarget(Public.targetScore);

		spriteNumberLevel = new AnimatedSprite[2];
		for (int i = 0; i < 2; i++) {
			spriteNumberLevel[i] = new AnimatedSprite(84 - i * 14, 36,
					mResourcesManager.mTiledTextureRegionNumberLevel_Player,
					VBOM);
		}
		updateNumberLevel(Public.LEVEL_CURRENT);

		mEntityBackGround.attachChild(mBackGround);
		mBackGround.attachChild(mPanel);
		mBackGround.attachChild(mTimeBrown);
		mBackGround.attachChild(mTimeBlue);
		mBackGround.attachChild(mTime);
		mBackGround.attachChild(mPause);
		mBackGround.attachChild(mMap);
		/* -------- score --------- */
		mPanel.attachChild(mScore[0]);

		attachChild(mEntityBackGround);

	}

	public void initPlayer() {
		fruitMananger = FruitManager.getINSTANCE();
		mEntityFruit = new Entity();
		fruitMananger.initial(Public.SUM_FRUIT_CURRENT, this, mEntityFruit);
		this.attachChild(mEntityFruit);
		this.setOnSceneTouchListener(this);
		this.registerUpdateHandler(mEntityFruit);
	}

	public void initScreenPauseGame() {
		checkpause = true;
		sumTime = T2 - T1;
		for (int i = 0; i < 7; i++) {
			for (int j = 0; j < 7; j++) {
				this.unregisterTouchArea(fruitMananger.INSTANCE.mapFruit[i][j]
						.getFruitNomall());
			}
		}
		this.unregisterTouchArea(mPause);

		mEntity_PauseGame = new Entity();
		spriteBackground_PauseGame = new Sprite(0, 0,
				mResourcesManager.mTextureRegionBackground_Player2, VBOM);
		spriteBackground_PauseGame.setAlpha(0.7f);

		spritePauseGame_PauseGame = new Sprite(Public.WIDTH_SCREEN / 2
				- mResourcesManager.mTextureRegionPause_Player2.getWidth() / 2,
				Public.HEIGHT_SCREEN
						/ 2
						- mResourcesManager.mTextureRegionMenu_Player2
								.getHeight() - 100,
				mResourcesManager.mTextureRegionPause_Player2, VBOM);

		spriteMenu_PauseGame = new Sprite(Public.WIDTH_SCREEN / 2
				- mResourcesManager.mTextureRegionMenu_Player2.getWidth() / 2,
				Public.HEIGHT_SCREEN
						/ 2
						- mResourcesManager.mTextureRegionMenu_Player2
								.getHeight() / 2,
				mResourcesManager.mTextureRegionMenu_Player2, VBOM) {
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				detackScreenPauseGame(1);
				return true;
			}
		};
		this.registerTouchArea(spriteMenu_PauseGame);

		spriteResume_PauseGame = new Sprite(
				Public.WIDTH_SCREEN
						/ 2
						- mResourcesManager.mTextureRegionResume_Player2.getWidth()
						/ 2,
				Public.HEIGHT_SCREEN
						/ 2
						+ mResourcesManager.mTextureRegionMenu_Player2
								.getHeight() / 2 + 20,
				mResourcesManager.mTextureRegionResume_Player2, VBOM) {
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				detackScreenPauseGame(2);
				return true;
			}
		};
		this.registerTouchArea(spriteResume_PauseGame);

		spriteOnAudio_PauseGame = new Sprite(10, 20,
				mResourcesManager.mOnSound_Player, VBOM) {
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				Public.AUDIO = false;
				mEntity_PauseGame.detachChild(spriteOnAudio_PauseGame);
				detackSound(spriteOffAudio_PauseGame);
				return true;
			}
		};
		this.registerTouchArea(spriteOnAudio_PauseGame);

		spriteOffAudio_PauseGame = new Sprite(10, 20,
				mResourcesManager.mOffSound_Player, VBOM) {
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				Public.AUDIO = true;
				// mEntity_PauseGame.detachChild(spriteOffAudio_PauseGame);
				// mEntity_PauseGame.attachChild(spriteOnAudio_PauseGame);
				return true;
			}
		};
		this.registerTouchArea(spriteOffAudio_PauseGame);

		mEntity_PauseGame.attachChild(spriteBackground_PauseGame);
		mEntity_PauseGame.attachChild(spritePauseGame_PauseGame);
		mEntity_PauseGame.attachChild(spriteMenu_PauseGame);
		mEntity_PauseGame.attachChild(spriteResume_PauseGame);
		mEntity_PauseGame.attachChild(setAudio(Public.AUDIO));

		attachChild(mEntity_PauseGame);
	}

	public void detackSound(Sprite sprite) {
		mEntity_PauseGame.attachChild(sprite);
	}

	public Sprite setAudio(boolean audio) {
		if (audio) {
			// spriteOnAudio_PauseGame = new Sprite(10, 20,
			// mResourcesManager.mOnSound_Player, VBOM) {
			// public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
			// float pTouchAreaLocalX, float pTouchAreaLocalY) {
			// Public.AUDIO = false;
			// mEntity_PauseGame.detachChild(spriteOnAudio_PauseGame);
			// mEntity_PauseGame.attachChild(setAudio(Public.AUDIO));
			// return true;
			// }
			// };
			// this.unregisterTouchArea(spriteOffAudio_PauseGame);
			// this.registerTouchArea(spriteOnAudio_PauseGame);
			return spriteOnAudio_PauseGame;
		} else {
			// spriteOffAudio_PauseGame = new Sprite(10, 20,
			// mResourcesManager.mOffSound_Player, VBOM) {
			// public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
			// float pTouchAreaLocalX, float pTouchAreaLocalY) {
			// Public.AUDIO = true;
			// mEntity_PauseGame.detachChild(spriteOffAudio_PauseGame);
			// mEntity_PauseGame.attachChild(spriteOnAudio_PauseGame);
			// return true;
			// }
			// };
			// this.unregisterTouchArea(spriteOnAudio_PauseGame);
			// this.registerTouchArea(spriteOffAudio_PauseGame);
			return spriteOffAudio_PauseGame;
		}

	}

	public void detackScreenPauseGame(int n) {
		if (n == 1) {
			ScenesManager.INSTAND.loadPlayerToMenu();
			return;
		}
		checkpause = false;
		T2 = T1 = System.currentTimeMillis();
		for (int i = 0; i < 7; i++) {
			for (int j = 0; j < 7; j++) {
				this.registerTouchArea(fruitMananger.INSTANCE.mapFruit[i][j]
						.getFruitNomall());
			}
		}
		this.registerTouchArea(mPause);
		this.unregisterTouchArea(spriteMenu_PauseGame);
		this.unregisterTouchArea(spriteResume_PauseGame);

		mEntity_PauseGame.detachChildren();
		detachChild(mEntity_PauseGame);

	}

	public void draw() {
		fruitMananger.initial(Public.SUM_FRUIT_CURRENT, this, mEntityFruit);

	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		if (pSceneTouchEvent.isActionUp()) {

			fruitMananger.updateGame();
			fruitMananger.mOpenGame = true;
		}
		return false;
	}

	public void updateScore(int score) {
		int temp = score;
		int swap = 0;
		int leng = 0;

		if (temp == 0) {
			mScore[0].setCurrentTileIndex(0);
			currentLeng = 0;
			return;
		}

		for (int i = 1; i <= currentLeng; i++) {
			mPanel.detachChild(mScore[i]);
		}

		while (temp > 0) {
			swap = temp % 10;
			if (leng > 0)
				mPanel.attachChild(mScore[leng]);
			mScore[leng].setCurrentTileIndex(swap);

			leng++;
			currentLeng = leng - 1;
			temp = temp / 10;
		}
	}

	public void updateScoreTarget(int score) {
		int temp = score;
		int swap = 0;
		int leng = 0;

		while (temp > 0) {
			swap = temp % 10;
			mTargetScore[leng].setCurrentTileIndex(swap);
			mPanel.attachChild(mTargetScore[leng]);
			leng++;
			currentLeng = leng - 1;
			temp = temp / 10;
		}
	}

	public void updateNumberLevel(int numberlevel) {
		int temp = numberlevel;
		Log.d("nhat quang",
				"=================================gia tri cua numberlevel: ================================================"
						+ Integer.toString(numberlevel));
		int swap = 0;
		int leng = 0;

		while (temp > 0) {
			swap = temp % 10;
			spriteNumberLevel[leng].setCurrentTileIndex(swap);
			mPanel.attachChild(spriteNumberLevel[leng]);
			leng++;
			currentLeng = leng - 1;
			temp = temp / 10;
		}
	}

	public boolean checkPause(float x, float y) {
		return true;
	}

	public void setLevel(int level) {
	}

	public void completeGame() {
		for (int i = 0; i < 7; i++) {
			for (int j = 0; j < 7; j++) {
				this.unregisterTouchArea(fruitMananger.INSTANCE.mapFruit[i][j]
						.getFruitNomall());
			}
		}
		// this.attachChild(mEntityGameOver);

	}

	// public void restartGame() {
	// mEntityGameOver.detachChildren();
	// this.unregisterTouchArea(spriteMenu);
	// this.unregisterTouchArea(spriteRestart);
	// this.unregisterTouchArea(spriteNext);
	// this.detachChild(mEntityGameOver);
	//
	// mEntityFruit.detachChildren();
	// fruitMananger.initial(Public.LEVEL_CURRENT, this, mEntityFruit);
	// }

	public void initControll() {

	}

	 @Override
	 protected void onManagedUpdate(float pSecondsElapsed) {
		 Log.d("", "tong so qua : " +Integer.toString(fruitMananger.sumFruit));
//	 T2 = System.currentTimeMillis();
//	 if ((T2 - T1) > 990 && !checkpause) {
//	 mTimeBlue.setPosition(mTimeBlue.getX() - 2, mTimeBlue.getY());
//	 T1 = T2;
//	 }
//	  if ((T2 - T0) > Public.timeLevel * 1000 && !checkpause) {
//	  if (fruitMananger.score > Public.targetScore)
//	  checkpause = true;
//	  completeGame();
//	  }
//	  if (FruitManager.INSTANCE.isUpdateScore) {
//	  updateScore(FruitManager.INSTANCE.score);
//	  FruitManager.INSTANCE.isUpdateScore = false;
//	  }
	 super.onManagedUpdate(pSecondsElapsed);
	 }

	public void onBackKeyPressed() {
		try {
			ScenesManager.getInstance().loadPlayerToMenu();
		} catch (Exception e) {
			mActivity.runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(mActivity,
							"Thao tác bị lỗi vui lòng thử lại",
							Toast.LENGTH_SHORT).show();
				}
			});
		}
	}
}